package com.itheima.service.impl;

import com.alibaba.druid.util.StringUtils;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.dao.CheckGroupDao;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBen;
import com.itheima.pojo.CheckGroup;
import com.itheima.service.CheckGroupService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class CheckGroupServiceImpl implements CheckGroupService {
    @Autowired
    private CheckGroupDao checkGroupDao;

    @Override
    @Transactional
    public void add(CheckGroup checkGroup, List<Integer> checkitemIds) {
        //添加检查组信息
        checkGroupDao.add(checkGroup);
        Integer checkGroupId = checkGroup.getId();
        if (null != checkitemIds) {
            for (Integer checkitemId : checkitemIds) {
                checkGroupDao.addCheckGroupCheckItem(checkGroupId, checkitemId);
            }
        }
    }

    @Override
    public PageResult<CheckGroup> findPage(QueryPageBen queryPageBean) {
        //使用分页插件
        PageHelper.startPage(queryPageBean.getCurrentPage(), queryPageBean.getPageSize());
        if (!StringUtils.isEmpty(queryPageBean.getQueryString())) {
            // 如果有条件， 模糊查询 拼接%%
            queryPageBean.setQueryString("%" + queryPageBean.getQueryString() + "%");
        }
        // 查询  Page<E> extends ArrayList<E>  implement List
        Page<CheckGroup> pageInfo = checkGroupDao.findByCondition(queryPageBean.getQueryString());
        return new PageResult<CheckGroup>(pageInfo.getTotal(), pageInfo.getResult());
    }

    @Override
    public CheckGroup findById(int id) {

        return checkGroupDao.findById(id);
    }


    @Override
    public List<Integer> findCheckItemIdsByCheckGroupId(int id) {
        return checkGroupDao.findCheckItemIdsByCheckGroupId(id);
    }


    @Override
    @Transactional
    public void update(CheckGroup checkGroup, List<Integer> checkitemIds) {
        //1. 更新检查组信息
        checkGroupDao.update(checkGroup);
        //2. 获取检查组id
        Integer checkGroupId = checkGroup.getId();
        //3. 先删除旧关系
        checkGroupDao.deleteCheckGroupCheckItem(checkGroupId);
        //4. 遍历选中的检查项id数组，空判断
        if (null != checkitemIds) {
            for (Integer checkitemId : checkitemIds) {
                //5. 添加检查组与检查项的新关系
                checkGroupDao.addCheckGroupCheckItem(checkGroupId, checkitemId);
            }
        }
        //6. 事务控制
    }

    @Override
    public void deleteByid(int id) {
        int low = checkGroupDao.findCountByCheckItemId(id);
        if (low > 0) {
            throw new MyException("该检查项有绑定的检查");
        }
        checkGroupDao.delete(id);
    }

    @Override
    public List<CheckGroup> findAll() {
      return   checkGroupDao.findAll();

    }

}

